import AuthService from '@/api/auth'
import { getTimeDifferenceInSeconds, isTimeExpired } from '@/utils/global'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

let timer: any
export const useAuthStore = defineStore('auth', () => {
    const token = ref<string | null>(localStorage.getItem('authToken'))
    const expirationOffsetMinutes = ref<number>(600) // 过期时间的偏移时间 秒 10分钟
    const isExpires = ref<boolean>(false) // 是否过期
    const isRenewal = ref<boolean>(false) // 是否续期

    // 判断token是否存在
    const isAuthenticated = computed(() => !!token.value)

    // 设置token
    const setToken = (newToken: string, expired_at: string) => {
        token.value = newToken
        isExpires.value = false
        isRenewal.value = false
        localStorage.setItem('authToken', newToken)
        localStorage.setItem('expired_at', expired_at)
        scheduleTokenExpirationCheck()
    }

    // 获取token
    const getToken = () => {
        token.value = localStorage.getItem('authToken')
        const expired_at = localStorage.getItem('expired_at') || ''
        if (!isTimeExpired(expired_at)) {
            scheduleTokenExpirationCheck()
        }
    }

    // 清除token
    const clearToken = () => {
        token.value = null
        localStorage.removeItem('authToken')
        localStorage.removeItem('expired_at')
    }

    // 计算token过期时间
    const scheduleTokenExpirationCheck = () => {
        const expired_at = localStorage.getItem('expired_at') || ''

        if (expired_at && !isTimeExpired(expired_at)) {
            timer = setTimeout(
                () => {
                    clearTimeout(timer)
                    // 直接刷新token
                    AuthService.refreshToken()
                },
                getTimeDifferenceInSeconds(expired_at, expirationOffsetMinutes.value),
            )
        } else {
            // 直接重新登录
            isExpires.value = true
        }
    }

    return { token, isExpires, isRenewal, isAuthenticated, setToken, getToken, clearToken, scheduleTokenExpirationCheck }
})
